#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time   :2021/12/13
# @Author :CJX
# @File   :PH_controller.py
import serial
import time
import binascii
import struct


def PH_enter_calibration(choice):
    instructions = 0
    str1 = 0
    a1 = 0
    s = serial.Serial("/dev/ttySC3", 9600)
    if choice == 4:
        instructions = "010600020001E9CA"
    elif choice == 6:
        instructions = "010600010000D80A"
    while a1 <= 1:
        hex_str = bytes.fromhex(instructions)
        s.write(hex_str)
        n = s.inWaiting()
        a1 = a1 + 1
        if n:
            str1 = binascii.b2a_hex(s.read(n))
        time.sleep(1)
    s.flushInput()
    string = str1.decode()
    return string


def PH_controller(choice):
    instructions = 0
    str1 = 0
    a1 = 0
    s = serial.Serial("/dev/ttySC3", 9600)
    if choice == 4:
        instructions = "0106000500FFD98B"
    elif choice == 6:
        instructions = "0106000400FF884B"
    while a1 <= 1:
        hex_str = bytes.fromhex(instructions)
        s.write(hex_str)
        n = s.inWaiting()
        a1 = a1 + 1
        if n:
            str1 = binascii.b2a_hex(s.read(n))
        time.sleep(1)
    s.flushInput()
    string = str1.decode()
    return string


def PH_num():
    str1 = 0
    a1 = 0
    s = serial.Serial("/dev/ttySC3", 9600)
    instructions = "01040000000131CA"
    while a1 <= 1:
        hex_str = bytes.fromhex(instructions)
        s.write(hex_str)
        n = s.inWaiting()
        a1 = a1 + 1
        if n:
            str1 = binascii.b2a_hex(s.read(n))
        time.sleep(1)
    s.flushInput()
    try:
        number = int(str1[6:10], 16)  # 真实数值还需要除100
    except:
        return 0
    return number


def PH_start():
    str1 = 0
    a1 = 0
    s = serial.Serial("/dev/ttySC3", 9600)
    instructions = "0106000600FF298B"
    while a1 <= 1:
        hex_str = bytes.fromhex(instructions)
        s.write(hex_str)
        n = s.inWaiting()
        a1 = a1 + 1
        if n:
            str1 = binascii.b2a_hex(s.read(n))
        time.sleep(1)
    s.flushInput()
    return str1
